/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameOnline.session;

import gameOnline.exception.ExistingPlayerException;
import gameOnline.persistance.Player;
import gameOnline.persistance.PlayerStatus;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;

/**
 * Représente la session d'un joueur.
 * Implémente l'interface GameClubSessionRemote.
 *
 * @author J. Harnetiaux
 * @version 1.0
 */
@Stateless
public class GameOnlineSession implements GameOnlineSessionRemote {

    @javax.persistence.PersistenceContext(unitName = "GameOnline-ejbPU")
    private EntityManager em;

    @Override
    public void persist(Object obj) {
        em.persist(obj);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Override
    public void remove(Object obj) {
        em.remove(em.merge(obj));
    }

    @Override
    public void merge(Object obj) {
        em.merge(obj);
    }

    @Override
    public Player login(String login, String password) {
        return (Player)em.createNamedQuery("findPlayer").setParameter("login", login).setParameter("password", password).getSingleResult();
    }

    @Override
    public void register(Player player) throws ExistingPlayerException {
        if(findAllPlayers().contains(player)) {
            throw new ExistingPlayerException("Ce joueur existe déjà !");
        }
        persist(player);
    }

    @Override
    public List findAllPlayers() {
        return em.createNamedQuery("findAllPlayers").getResultList();
    }
    
    @Override
    public List findConnectPlayers() {
        return em.createNamedQuery("findConnectPlayers").setParameter("statut", PlayerStatus.ONLINE).getResultList();
    }
}
